﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

using System.Web;
using System.Collections.Specialized;
using System.Xml;

namespace MSL.Utility.Config
{
    /// <summary>
    /// 配置文件操作类
    /// </summary>
    public sealed class Helper
    {
        #region 是否存在

        /// <summary>
        /// 配置项是否存在
        /// AppSettings ConnectionStrings
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExistApp(string key)
        {
            bool returnValue = false;
            if (ConfigurationManager.ConnectionStrings[key] == null && ConfigurationManager.AppSettings[key] == null)
            {
                returnValue = true;
            }
            return returnValue;
        }
        #endregion

        #region 获取AppSettings

        /// <summary>
        /// 获取配置文件中的字符串 使用AppSettings
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetApp(string key)
        {
            string cacheKey = "appsettings-" + key;
            object cache = Cache.Instance.Get(cacheKey);
            if (cache == null)
            {
                try
                {
                    cache = ConfigurationManager.AppSettings[key];
                    if (cache != null)
                    {
                        Cache.Instance.Add(cacheKey, cache, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
                    }
                }
                catch (Exception)
                {
                    //throw new Exception();
                }
            }
            return cache.ToString();
        }
        #endregion

        #region 获取ConnectionStrings

        /// <summary>
        /// 获取配置文件中的字符串 并缓存 使用ConnectionStrings
        /// </summary>
        /// <param name="key"></param>
        /// <param name="providerName">返回数据库类型</param>
        /// <returns></returns>
        public static string GetProviderApp(string key, out string providerName)
        {
            string connKey = "connectionstrings-" + key;
            object connValue = Cache.Instance.Get(connKey);

            string provideKey = "providername-" + key;
            providerName = (string)Cache.Instance.Get(provideKey);
            if (connValue == null)
            {
                try
                {
                    connValue = ConfigurationManager.ConnectionStrings[key];
                    providerName = ConfigurationManager.ConnectionStrings[key].ProviderName;
                    if (connValue != null)
                    {
                        Cache.Instance.Add(connKey, connValue, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
                        Cache.Instance.Add(provideKey, providerName, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
                    }
                }
                catch
                {

                }
            }
            return connValue.ToString();
        }

        #endregion

        #region 自定义App.config配置项

        /// <summary>
        /// 获取自定义App.config配置项
        /// 例如：根目录\\setup\\App.config
        /// </summary>
        /// <param name="configPath">配置文件路径</param>
        /// <param name="nodeName">节点名</param>
        /// <param name="appInnerXml">节点InnerXml</param>
        /// <returns>节点value</returns>
        public static string GetApp(string configPath, string nodeName, out string appInnerXml)
        {
            string nodeValue = string.Empty;
            appInnerXml = string.Empty;
            try
            {
                if (String.IsNullOrEmpty(configPath))
                {
                    configPath = HttpRuntime.AppDomainAppPath + "\\setup\\App.config";
                }
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(configPath);
                //如果没有则添加 
                if (xmlDoc.SelectNodes("//appSettings").Count == 0)
                {
                    xmlDoc.DocumentElement.AppendChild(xmlDoc.CreateElement("appSettings"));
                }
                foreach (XmlNode xn1 in xmlDoc.SelectNodes("/configuration/appSettings/add"))
                {
                    if (xn1.Attributes["key"].Value == nodeName)
                    {
                        appInnerXml = xn1.InnerXml;
                        nodeValue = xn1.Attributes["value"].Value;
                    }
                }
            }
            catch (Exception)
            { }
            return nodeValue;
        }
        #endregion

        #region 获得自定义节点内容

        /// <summary>
        /// 获得自定义节点内容
        /// </summary>
        /// <param name="preNodeName">自定义父节点名</param>
        /// <param name="nodeName">节点名</param>
        /// <returns></returns>
        public static string GetApp(string preNodeName, string nodeName)
        {
            object a = ((NameValueCollection)ConfigurationSettings.GetConfig("AppConfig/" + preNodeName))[nodeName];
            return a.ToString();
        }

        /// <summary>
        /// IConfigurationSectionHandler 成员
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="configContext"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        private object Create(object parent, object configContext, XmlNode section)
        {
            NameValueCollection configs;
            NameValueSectionHandler baseHandler = new NameValueSectionHandler();
            configs = (NameValueCollection)baseHandler.Create(parent, configContext, section);
            return configs;
        }
        #endregion
    }
}

